/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("cw_djlc_configuration_tradition",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Finance.IServices;
using VOL.Core.Filters;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using OfficeOpenXml;
using sysio = System.IO;
using sysnet = System.Net;
using System.IO;
using OfficeOpenXml.Style;
using System.Linq;
using VOL.Entity.DomainModels;
using VOL.Core.DBManager;
using Microsoft.AspNetCore.Authorization;

namespace VOL.Finance.Controllers
{
    public partial class cw_djlc_configuration_traditionController
    {
        private readonly Icw_djlc_configuration_traditionService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public cw_djlc_configuration_traditionController(
            Icw_djlc_configuration_traditionService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        WebResponseContent webResponse = new WebResponseContent();

        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("GetPageData"), AllowAnonymous]
        public override ActionResult GetPageData([FromBody] PageDataOptions loadData)
        {
             return base.GetPageData(loadData);
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("del")]
        public override ActionResult Del([FromBody] object[] keys)
        {
            return base.Del(keys);
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("Import1")]
        public ActionResult Import1(List<IFormFile> fileInput,string type, string cw_djlc_djzb_id)
        {
            if (fileInput == null || fileInput.Count == 0)
            {
                return Json(webResponse.Error("请选择文件！"));
            }
            if (string.IsNullOrEmpty(cw_djlc_djzb_id))
            {
                return Json(webResponse.Error("参数丢失，请重新上传！"));
            }
            
            return Json(_service.Import_Configuration(fileInput,cw_djlc_djzb_id));
        }

        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpGet, Route("DownLoadTemplate1")]
        public ActionResult DownLoadTemplate1()
        {
            List<dynamic> list = new List<dynamic>();
            string fileName = "传统车配置表";
            string fullFileName = ExportNewEnergyfcExcel(list, fileName);
            return File(sysio.File.ReadAllBytes(fullFileName), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        [ApiActionPermission()]
        public override ActionResult Export([FromBody] PageDataOptions loadData)
        {
            String jsonstr = loadData.Wheres;
            List<SearchParameters> parameters = loadData.Wheres.DeserializeObject<List<SearchParameters>>();
            string tsql = "select serial_number,new_materialnum,brevity_code,announcement_type,vehicle_model,driving_form,fuel_type,allowed_total_weight,cage,wheel_base,applicable_jacket,car_frame,suspension_type,ct_engine_series,ct_engine_type,ct_intake_heating,fuel_tank,brake_type,plate_spring_number,speed_ratio,tyre,rim,seat,fairing,fender_rear_wheel,tire_pressure_monitoring,inverter,car_mounted_multimedia,video_assistance_system,battery_capacity,ct_parking_air_conditioner,ct_independent_heater,car_refrigerator,ct_retarder,saddle,constant_cruising,ct_in_cylinder_braking,ct_remote_throttle,maximum_speed_limit,ct_fan_clutch,ct_fuel_preliminary_filter,ct_air_filter,fan_lower_baffle,ct_clutch,steering_engine,transmission_model,transmission_take_up,ct_variable_speed_control_mode,mandrel_form,thrust_rod_type,front_crosswise_bar,front_axle_specification,front_alxe_free_preserve,back_alxe_model,back_alxe_free_preserve,interwheel_differential_lock,interaxial_differential_lock,steering_wheel_guide_pattern,front_wheel_blowout_device,electronic_brake_type,electronic_brake_modle,cab_suspension,front_bumper,front_mask_color,fender,skylight,upper_berth,door_lower_fascia,door_lock,air_conditioner,steering_wheel,daytime_running_light,back_assembly_light_model,power_controller,ct_joint_pass,auxiliary_safety_system,battery_type,battery_tray_type,ct_air_filter_arrangement,ct_silencer_arrangement,ct_urea_tank_layout,ct_fuel_tank_layout,ct_battery_arrangement,ct_design_quality,ct_remark from cw_djlc_configuration_tradition where del_flag = 0 ";
            foreach (SearchParameters a in parameters)
            {
                if (a.Value!=null&& a.Name!=null)
                {
                    tsql = tsql + " and " + a.Name + " = " + "\'" + Convert.ToString(a.Value) + "\'";
                } 
            }
            List<dynamic> list = DBServerProvider.SqlDapper.QueryList<dynamic>(tsql, null).ToList();
            string fileName = "传统车配置表.xlsx";
            string fullFileName = ExportNewEnergyfcExcel(list,fileName);
            return File(sysio.File.ReadAllBytes(fullFileName), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
        }

        private string ExportNewEnergyfcExcel(List<dynamic> list, string fileName)
        {
            string path = null;
            path = path ?? $"Download/ExcelExport/{DateTime.Now.ToString("yyyyyMMdd")}/";
            string fullPath = path.MapPath();
            fileName = Guid.NewGuid() + "_" + fileName;
            if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
            ExcelPackage excel = new ExcelPackage();
            ExcelWorksheet sheet = excel.Workbook.Worksheets.Add("sheet1");
            sheet.Cells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            sheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            sheet.Cells["A1"].Value = "固化配置项";
            sheet.Cells["A1:N1"].Merge = true;
            sheet.Cells["O1"].Value = "市场可选项";
            sheet.Cells["O1:AJ1"].Merge = true;
            sheet.Cells["AK1"].Value = "技术配置项";
            sheet.Cells["AK1:BZ1"].Merge = true;
            sheet.Cells["CA1"].Value = "关键布置项目";
            sheet.Cells["CA1:CE1"].Merge = true;
            sheet.Cells["CF1"].Value = "其他";
            sheet.Cells["CF1:CG1"].Merge = true;

            sheet.Cells["A2"].Value = "序号";
            sheet.Cells["B2"].Value = "新车型号";
            sheet.Cells["C2"].Value = "简码";
            sheet.Cells["D2"].Value = "公告型号";
            sheet.Cells["E2"].Value = "车型";
            sheet.Cells["F2"].Value = "驱动形式";
            sheet.Cells["G2"].Value = "燃料";
            sheet.Cells["H2"].Value = "允许车货总重";
            sheet.Cells["I2"].Value = "驾驶室";
            sheet.Cells["J2"].Value = "轴距";
            sheet.Cells["K2"].Value = "适用上装";
            sheet.Cells["L2"].Value = "车架";
            sheet.Cells["M2"].Value = "悬架型式";
            sheet.Cells["N2"].Value = "发动机系列";
            sheet.Cells["O2"].Value = "发动机型号";
            sheet.Cells["P2"].Value = "进气加热";      //"转向机";
            sheet.Cells["Q2"].Value = "燃料箱";
            sheet.Cells["R2"].Value = "制动型式";
            sheet.Cells["S2"].Value = "板簧片数";
            sheet.Cells["T2"].Value = "速比";
            sheet.Cells["U2"].Value = "轮胎";
            sheet.Cells["V2"].Value = "轮辋";
            sheet.Cells["W2"].Value = "座椅";
            sheet.Cells["X2"].Value = "导流罩";
            sheet.Cells["Y2"].Value = "后轮上挡泥板";
            sheet.Cells["Z2"].Value = "胎压监测";
            sheet.Cells["AA2"].Value = "逆变器";

            sheet.Cells["AB2"].Value = "车载多媒体";
            sheet.Cells["AC2"].Value = "视频辅助系统";
            sheet.Cells["AD2"].Value = "蓄电池容量";
            sheet.Cells["AE2"].Value = "驻车空调";
            sheet.Cells["AF2"].Value = "独立加热器";
            sheet.Cells["AG2"].Value = "车载冰箱";
            sheet.Cells["AH2"].Value = "缓速器";
            sheet.Cells["AI2"].Value = "鞍座";
            sheet.Cells["AJ2"].Value = "定速巡航";
            sheet.Cells["AK2"].Value = "缸内制动";
            sheet.Cells["AL2"].Value = "远程油门";
            sheet.Cells["AM2"].Value = "最高车速限制";
            sheet.Cells["AN2"].Value = "风扇离合器";
            sheet.Cells["AO2"].Value = "燃油粗滤器";
            sheet.Cells["AP2"].Value = "空滤器";
            sheet.Cells["AQ2"].Value = "风扇下挡板";
            sheet.Cells["AR2"].Value = "离合器";
            sheet.Cells["AS2"].Value = "转向机"; //转向机

            sheet.Cells["AT2"].Value = "变速器型号";
            sheet.Cells["AU2"].Value = "变速器取力器";
            sheet.Cells["AV2"].Value = "变速操纵型式";
            sheet.Cells["AW2"].Value = "芯轴形式";
            sheet.Cells["AX2"].Value = "推力杆型式";
            sheet.Cells["AY2"].Value = "前横向稳定杆";
            sheet.Cells["AZ2"].Value = "前桥规格";
            sheet.Cells["BA2"].Value = "前桥免维护";
            sheet.Cells["BB2"].Value = "后桥型号";

            sheet.Cells["BC2"].Value = "后桥免维护";
            sheet.Cells["BD2"].Value = "轮间差速锁";
            sheet.Cells["BE2"].Value = "轴间差速锁";
            sheet.Cells["BF2"].Value = "转向轮导向花纹";
            sheet.Cells["BG2"].Value = "前轮爆胎应急装置";
            sheet.Cells["BH2"].Value = "电子制动型式";
            sheet.Cells["BI2"].Value = "电子制动品牌";
            sheet.Cells["BJ2"].Value = "驾驶室悬置";
            sheet.Cells["BK2"].Value = "前保险杠";
            sheet.Cells["BL2"].Value = "前面罩颜色";
            sheet.Cells["BM2"].Value = "挡泥板";
            sheet.Cells["BN2"].Value = "天窗";
            sheet.Cells["BO2"].Value = "上卧铺";
            sheet.Cells["BP2"].Value = "车门下饰板";
            sheet.Cells["BQ2"].Value = "门锁";
            sheet.Cells["BR2"].Value = "空调";
            sheet.Cells["BS2"].Value = "方向盘";
            sheet.Cells["BT2"].Value = "日间行车灯";
            sheet.Cells["BU2"].Value = "后组合灯型式";
            sheet.Cells["BV2"].Value = "电源控制器";
            sheet.Cells["BW2"].Value = "远程车载终端"; //联合通
            sheet.Cells["BX2"].Value = "辅助安全系统";
            sheet.Cells["BY2"].Value = "蓄电池类型";
            sheet.Cells["BZ2"].Value = "蓄电池托盘型式";
            sheet.Cells["CA2"].Value = "空滤布置";
            sheet.Cells["CB2"].Value = "消声器布置";
            sheet.Cells["CC2"].Value = "尿素罐布置";
            sheet.Cells["CD2"].Value = "燃料箱布置";
            sheet.Cells["CE2"].Value = "蓄电池布置";
            sheet.Cells["CF2"].Value = "设计质量（kg）";
            sheet.Cells["CG2"].Value = "备注";

            if (!list.IsNullOrEmpty() && list.Count > 0)
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    int j = 0;
                    int rowIndex = i + 3;
                    int columnIndex = j + 1;
                    foreach (KeyValuePair<string, object> col in list[i])
                    {
                        string aa = col.Key;//属性
                        if (col.Value == null || col.Value.IsNullOrEmpty() || col.Value.Equals("null"))
                        {
                            sheet.Cells[rowIndex, columnIndex].Value = "";
                        }
                        else
                        {
                            string bb = col.Value.ToString() ?? "";//值
                            sheet.Cells[rowIndex, columnIndex].Value = bb;
                        }
                        columnIndex++;
                    }
                }
            }
            FileInfo file = new FileInfo(fullPath + fileName);
            excel.SaveAs(file);
            return fullPath + fileName;
        }

    }
}
